package com.lsp.base.utils.rxpreference;

import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import com.f2prateek.rx.preferences.Preference;
import java.lang.reflect.Type;

/**
 * @author com.lsp.ibxs
 * @created 16/11/11 13:47
 */
public class JsonPreferenceAdapter<T> implements Preference.Adapter<T> {
  private JsonConverter mJsonConverter;
  private Type mType;

  public static <T> JsonPreferenceAdapter<T> forClass(JsonConverter jsonConverter, Class<T> clazz) {
    return forType(jsonConverter, clazz);
  }

  public static <T> JsonPreferenceAdapter<T> forType(JsonConverter jsonConverter, Type type) {
    return new JsonPreferenceAdapter<>(jsonConverter, type);
  }

  private JsonPreferenceAdapter(JsonConverter jsonConverter, Type type) {
    this.mJsonConverter = jsonConverter;
    this.mType = type;
  }

  @Override public T get(@NonNull String key, @NonNull SharedPreferences preferences) {
    return mJsonConverter.fromJson(preferences.getString(key, null), mType);
  }

  @Override
  public void set(@NonNull String key, @NonNull T value, @NonNull SharedPreferences.Editor editor) {
    editor.putString(key, mJsonConverter.toJson(value));
  }
}
